package com.dqx.haoqiu.mvp.common.base;

import androidx.annotation.StringRes;

import com.dqx.haoqiu.mvp.R;
import com.xmjs.baselibrary.base.IBasePresenter;
import com.xmjs.baselibrary.base.IBaseView;
import com.xmjs.baselibrary.network.ResponseError;
import com.xmjs.baselibrary.utils.ToastUtil;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.inject.Inject;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;

import retrofit2.HttpException;

import static com.dqx.haoqiu.mvp.common.constant.ErrorCode.ACCOUNT_OR_PASSWORD_ERROR;
import static com.dqx.haoqiu.mvp.common.constant.ErrorCode.TOKEN_LOSE_EFFICACY;
import static com.dqx.haoqiu.mvp.common.constant.ErrorCode.UN_REGISTER;

/**
 * 基础Presenter
 * 作用：处理各种异常和错误
 */
public abstract class BasePresenter<V extends IBaseView> implements IBasePresenter {
    @Inject
    public V view;

    /**
     * 订阅事件
     */
    @Override
    public void subscribe() {

    }

    /**
     * 取消订阅
     */
    @Override
    public void unsubscribe() {

    }

    /**
     * 请求异常/错误处理
     *
     * @param e           异常
     * @param defErrorMsg 默认提示语
     * @param view
     */
    public void showNetworkError(Throwable e, @StringRes int defErrorMsg, IBaseView view) {
        view.hideLoadingView();

        //1.业务层错误（例如服务端定义的令牌失效）
        if (e instanceof ResponseError) {
            ResponseError error = ((ResponseError) e);
            if (error.getCode() == TOKEN_LOSE_EFFICACY.getValue()) {//登录令牌失效
                view.onReLogin();
                return;
            }

            if (error.getCode() == UN_REGISTER.getValue() //账号未注册
                    || error.getCode() == ACCOUNT_OR_PASSWORD_ERROR.getValue()) {//账号密码错误
                toast(error.getMessage());
                return;
            }

            //服务端定义的其他错误
            view.showError(R.mipmap.img_error, R.string.error_loading, R.string.refresh);
            return;
        }

        //2.协议层错误
        if (e instanceof HttpException
                || e instanceof ConnectException
                || e instanceof UnknownHostException
                || e instanceof SocketTimeoutException
                || e instanceof SocketException
                || e instanceof SSLException
                || e instanceof SSLHandshakeException) {
            view.showError(R.mipmap.img_network, R.string.error_no_network, R.string.refresh);
            return;
        }

        //3.其他错误（比如解析异常、空指针异常等本地异常）
        view.showError(R.mipmap.img_error, e.getLocalizedMessage(), R.string.refresh);
        return;
    }

    /**
     * 吐司
     *
     * @param resId
     */
    protected void toast(@StringRes int resId) {
        ToastUtil.getInstance().toast(resId);
    }

    /**
     * 吐司
     *
     * @param msg
     */
    protected void toast(String msg) {
        ToastUtil.getInstance().toast(msg);
    }
}
